#! /usr/bin/python3

import argparse

def argument():
    arg = argparse.ArgumentParser()
    arg.add_argument("--file", '-f', required = True, help = 'Fasta file name')
    return arg.parse_args()

def CalcSPScore(L: list, Llength: int) -> float:
    if len(L) != Llength:
        raise TypeError("Logic is error, in CalcSPScore")
    Sumpairs = 0
    SP = 0
    for i in range(Llength):
        if L[i] == '-': continue
        for j in range(i + 1, Llength):
            if L[i] == L[j]:
                SP += 1
            Sumpairs += 1
    if Sumpairs == 0: return 0
    return SP / Sumpairs

if __name__ == '__main__':
    arg = argument()
    f = open(arg.file)
    sequences = []
    thisline = []
    for line in f:
        if line.startswith(">"):
            if thisline != []: sequences.append(''.join(thisline))
            thisline = []
        else:
            thisline.append(line.strip())
    if thisline != []:
        sequences.append(''.join(thisline))
    # print(sequences)
    if len(sequences) < 1: 
        print("Error: this file has no sequences!!")
        exit(1)
    # Check the sequence is the same length
    seqlen1 = len(sequences[0])
    seqlen = [seqlen1]
    maxlen = seqlen1
    sequence_cnt = 1
    for i in range(1, len(sequences)):
        thislen = len(sequences[i])
        if thislen != seqlen1:
            print("Warning: The length of sequence " + str(i) + "(" + str(thislen) + ") is not same as sequence 0(" + str(seqlen1) + ")!!")
            maxlen = max(maxlen, thislen)
        seqlen.append(thislen)
        sequence_cnt += 1
    
    # Calcuate the Simliarity Score
    SP_Score = 0
    for place in range(0, maxlen):
        L = []
        for i in range(0, sequence_cnt):
            if seqlen[i] <= place: L.append('?')
            else: L.append(sequences[i][place])
        SP_Score += CalcSPScore(L, sequence_cnt)
    print("Similarity Score is: ", SP_Score / maxlen)